import os
import json
import datetime
from macro import MacroProject, KeyboardMacro, TextMacro, MouseMoveMacro, \
                  MouseMoveToImageMacro, MouseMacro, ScrollMacro, WaitMacro, WaitKeyMacro

class ApplicationModel:
    """应用程序数据模型"""
    def __init__(self):
        # 应用数据目录
        self.app_data_dir = os.path.join(os.path.expanduser("~"), ".macro_automation")
        self.image_dir = os.path.join(self.app_data_dir, "images")
        os.makedirs(self.image_dir, exist_ok=True)
        
        # 最近文件列表
        self.recent_projects = []
        self.recent_projects_max = 10
        self.load_recent_projects()
        
        # 当前宏工程
        self.current_project = None
        
        # 执行状态
        self.is_running = False
        self.is_recording = False
        
    def new_project(self):
        """创建新的宏工程"""
        self.current_project = MacroProject()
        return self.current_project
        
    def open_project(self, file_path):
        """打开宏工程"""
        project = MacroProject.load(file_path)
        if project:
            self.current_project = project
            self.add_to_recent_projects(file_path)
            return True
        return False
        
    def save_project(self, file_path=None):
        """保存宏工程"""
        if not self.current_project:
            return False
            
        if file_path:
            return self.current_project.save(file_path)
        else:
            return self.current_project.save()
            
    def add_macro_item(self, item_type, **kwargs):
        """添加宏命令项"""
        if not self.current_project:
            return None
            
        item_classes = {
            "keyboard": KeyboardMacro,
            "text": TextMacro,
            "mouse_move": MouseMoveMacro,
            "mouse_move_image": MouseMoveToImageMacro,
            "mouse": MouseMacro,
            "scroll": ScrollMacro,
            "wait": WaitMacro,
            "wait_key": WaitKeyMacro
        }
        
        item_class = item_classes.get(item_type)
        if not item_class:
            return None
            
        item = item_class(** kwargs)
        self.current_project.add_item(item)
        return item
        
    def remove_macro_item(self, item_id):
        """移除宏命令项"""
        if self.current_project:
            self.current_project.remove_item(item_id)
            
    def move_macro_item(self, from_index, to_index):
        """移动宏命令项位置"""
        if self.current_project:
            self.current_project.move_item(from_index, to_index)
            
    def load_recent_projects(self):
        """加载最近打开的工程列表"""
        recent_file = os.path.join(self.app_data_dir, "recent_projects.json")
        if os.path.exists(recent_file):
            try:
                with open(recent_file, 'r', encoding='utf-8') as f:
                    self.recent_projects = json.load(f)
            except Exception as e:
                print(f"加载最近文件列表失败: {str(e)}")
                self.recent_projects = []
    
    def save_recent_projects(self):
        """保存最近打开的工程列表"""
        recent_file = os.path.join(self.app_data_dir, "recent_projects.json")
        try:
            with open(recent_file, 'w', encoding='utf-8') as f:
                json.dump(self.recent_projects, f, ensure_ascii=False)
        except Exception as e:
            print(f"保存最近文件列表失败: {str(e)}")
    
    def add_to_recent_projects(self, file_path):
        """添加文件到最近列表"""
        # 如果已存在则移到前面
        if file_path in self.recent_projects:
            self.recent_projects.remove(file_path)
        
        # 添加到开头
        self.recent_projects.insert(0, file_path)
        
        # 限制数量
        if len(self.recent_projects) > self.recent_projects_max:
            self.recent_projects = self.recent_projects[:self.recent_projects_max]
        
        # 保存列表
        self.save_recent_projects()
    
    def get_macro_items(self):
        """获取宏命令列表"""
        if self.current_project:
            return self.current_project.items
        return []
        
    def get_macro_item(self, index):
        """获取指定索引的宏命令"""
        items = self.get_macro_items()
        if 0 <= index < len(items):
            return items[index]
        return None
